package com.yonyou.crm.sact.visit.service;

import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.enumeration.service.EnumBizServiceImpl;
import com.yonyou.crm.common.field.handler.FieldRelationHandler;
import com.yonyou.crm.common.field.relation.FieldRelation;
import com.yonyou.crm.common.field.relation.RefFieldRelation;
import com.yonyou.crm.common.page.entity.Page;
import com.yonyou.crm.cum.contact.service.ContactBizServiceImpl;
import com.yonyou.crm.cum.customer.entity.CustomerVO;
import com.yonyou.crm.sact.outwork.entity.TraceVO;
import com.yonyou.crm.sact.outwork.service.TraceBizServiceImpl;
import com.yonyou.crm.sact.schedule.entity.ScheduleTaskcardVO;
import com.yonyou.crm.sact.schedule.entity.ScheduleTypeEnum;
import com.yonyou.crm.sact.schedule.service.ScheduleBizServiceImpl;
import com.yonyou.crm.sact.schedule.service.ScheduleTaskcardBizServiceImpl;
import com.yonyou.crm.sact.taskcard.entity.SactTaskcardVO;
import com.yonyou.crm.sact.taskcard.service.SactTaskcardBizServiceImpl;
import com.yonyou.crm.sact.visit.entity.VisitsVO;
import com.yonyou.crm.sact.visitrule.entity.*;
import com.yonyou.crm.sact.visitrule.service.VisitruleBizServiceImpl;
import com.yonyou.crm.sys.modules.entity.MtObjTypeEnum;
import com.yonyou.crm.sys.org.service.SysOrgBizServiceImpl;
import com.yonyou.crm.sys.user.entity.UserVO;
import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Service
public class VisitsBizServiceImpl  extends BaseBizServiceImpl<VisitsVO>  {
	
	@Autowired
	private SysOrgBizServiceImpl orgService;
	@Autowired
	private EnumBizServiceImpl enumService;
	@Autowired
	private TraceBizServiceImpl traceService;
	@Autowired
	private ContactBizServiceImpl contactService;
	@Autowired
	private VisitruleBizServiceImpl visitruleService;
	@Autowired
	private SactTaskcardBizServiceImpl tcService;
	@Autowired
	private ScheduleBizServiceImpl scheduleService;
	@Autowired
	private ScheduleTaskcardBizServiceImpl stService;
	@Autowired
	private UserBizServiceImpl userService;
	
	/**
	 * 列表
	 * @param page
	 * @param paramMap
	 * @return
	 */
	public Page<VisitsVO> getList(Page<VisitsVO> page,Map<String, Object> paramMap) {
		
		Page<VisitsVO> visitPage = null;
		if (paramMap != null) {
			visitPage = super.pageSelect(VisitsVO.class, page, paramMap.keySet().toArray(new String[0]), paramMap.values().toArray(new Object[0]));
		}
		else {
			visitPage = super.pageSelect(VisitsVO.class, page, null, null);
		}
		
		transVisit(visitPage.getData());
		
		return visitPage;
	}
	
	/**
	 * 详情
	 * @param id
	 * @return
	 */
	public VisitsVO getDetail(Long id) {
		VisitsVO visit = super.getVOById(VisitsVO.class, id);
		CustomerVO customer = visit.getCumInfo();
		Integer refIndex = getRefIndex();
		//所有任务卡
		List<SactTaskcardVO> allTList = tcService.getRefList(null);
		if(refIndex == 1){
			Integer level = customer.getLevel();
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("tenantId", InvocationInfoProxy.getTenantid());
			param.put("refIndex", refIndex);
			param.put("cumLevel", level);
			List<VisitruleVO> vrList = dao.selectVoList(VisitruleVO.class, "getRefList", param);
			if(vrList != null && vrList.size() > 0){
				VisitruleVO visitRule = vrList.get(0);
				getVisitRule(id, visitRule, allTList);
				visit.setVisitRule(visitRule);
			}
		}else if(refIndex == 2){
			
		}else if(refIndex == 3){
		
		}
		transVisit(Arrays.asList(visit));
		return visit;
	}
	
	/**
	 * 转化拜访规则
	 * @param id
	 * @param visitRule
	 * @param allTList
	 */
	private void getVisitRule(Long id, VisitruleVO visitRule, List<SactTaskcardVO> allTList){ 
		List<VisitruleTaskcardVO> vrtList = visitRule.getTaskcardList();
		Iterator<SactTaskcardVO> allIterator = allTList.iterator();
		while (allIterator.hasNext()) {
			SactTaskcardVO allVO = allIterator.next();
			for (VisitruleTaskcardVO checkedVO : vrtList) {
				if (allVO.getId().equals(checkedVO.getTaskcardId())) {
					//翻译选中的任务卡名称
					checkedVO.setTaskcardName(allVO.getMtBiztypeName());
					checkedVO.setMtObjName(allVO.getMtObjName());
					checkedVO.setMtBiztypeName(allVO.getMtBiztypeName());
					//移除选中的任务卡
					allIterator.remove();
				}
			}
		}
		getTaskCardList(id, vrtList);
		
	}
	
	/**
	 * 转化任务卡
	 * @param id
	 * @param vrtList
	 */
	private void getTaskCardList(Long id, List<VisitruleTaskcardVO> vrtList) {
		for(VisitruleTaskcardVO vrt : vrtList){
			if(vrt.getMtObjId() != null && !vrt.getMtObjId().equals(new Long("0"))){
				String objType = vrt.getMtObjId().toString();
				List<Map<String, Object>> objectList = new ArrayList<Map<String,Object>>();
				if (String.valueOf(MtObjTypeEnum.CONTACT.getValue()).equals(objType)) {
					objectList = scheduleService.getContactList(id, vrt.getMtBiztypeId(), ScheduleTypeEnum.CUSVISIT.getValue());
					vrt.setContactList(objectList);
				} else if (String.valueOf(MtObjTypeEnum.LEAD.getValue()).equals(objType)) {
					objectList = scheduleService.getLeadList(id, vrt.getMtBiztypeId(), ScheduleTypeEnum.CUSVISIT.getValue());
					vrt.setLeadList(objectList);
				} else if (String.valueOf(MtObjTypeEnum.OPPORTUNITY.getValue()).equals(objType)) {
					objectList = scheduleService.getopportunityList(id, vrt.getMtBiztypeId(), ScheduleTypeEnum.CUSVISIT.getValue());
					vrt.setOpporList(objectList);
				} else if (String.valueOf(MtObjTypeEnum.COMPETITIVE.getValue()).equals(objType)) {
					//TODO 竞品采集
					
				} else {
					//nothing
				}
			}
		}
	}
		
	@Override
	protected void beforeSaveVO(VisitsVO vo) {
		
		super.beforeSaveVO(vo);
		
		Long loginUserID =  new Long(InvocationInfoProxy.getParameter("id"));
		Date date = new Date();
		
		vo.setTenantId(new Long(InvocationInfoProxy.getTenantid()));
		vo.setOrgId(new Long(InvocationInfoProxy.getParameter("orgid")));
		
		vo.setStatus(1);
		
		vo.setCreatedTime(date);
		vo.setCreatedUserId(loginUserID);
		
		vo.setOwnerUserId(loginUserID);
		
		vo.setSysCreatedTime(date);
		vo.setSysCreatedUserId(loginUserID);
	}
	
	public VisitsVO update(VisitsVO visit) {

		return super.updateVO(visit);
	}
	
	public void AutoCompleteVisit(Long id) {
		
		VisitsVO newVisit = getDetail(id);
		boolean checkFlag = checkStatus(newVisit);
		if (checkFlag) {
			VisitsVO visit = new VisitsVO();
			visit.setId(id);
			//设置完成状态
			visit.setStatus(3);
			update(visit);
		}
	}
	
	private boolean checkStatus(VisitsVO visit) {

		VisitruleVO visitRule = getVisitRule(visit);
		//TODO 根据拜访规则完成状态校验
		
		return false;
	}
	
	public VisitsVO summary(VisitsVO visit){
		update(visit);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("scheduleId", visit.getId());
		param.put("scheduleType", ScheduleTypeEnum.CUSVISIT.getValue());
		param.put("objType", 0);
		param.put("objBiztype", 0);
		param.put("written", 1);
		dao.updateSql(ScheduleTaskcardVO.class, "updateTaskcardStatus", param);
		Date nextDate = visit.getNextDate();
		//如果设置下次拜访时间，添加拜访计划
		if (nextDate != null) {
			visit = getDetail(visit.getId());
			VisitsVO visitNew = new VisitsVO();
			visitNew.setCumId(visit.getCumId());
			visitNew.setDate(nextDate);
			saveVO(visitNew);
		}

		return visit;
	}
	
	@Override
	protected void beforeUpdateVO(VisitsVO vo) {
		
		super.beforeUpdateVO(vo);

		vo.setSysModifiedTime(new Date());
		vo.setSysModifiedUserId(new Long(InvocationInfoProxy.getParameter("id")));
		
		vo.setModifiedTime(new Date());
		vo.setModifiedUserId(new Long(InvocationInfoProxy.getParameter("id")));
	}
	
	public int delete(Long id) {
		VisitsVO visit = new VisitsVO();
		visit.setId(id);
		return super.deleteVO(visit);
	}
	
	public VisitsVO location(Long id, TraceVO trace){
		TraceVO newtrace = traceService.saveVO(trace);
		long traceId = newtrace.getId();

		VisitsVO visit = new VisitsVO();
		visit.setId(id);
		visit.setTraceId(traceId);
		update(visit);
		
		return visit;
	}
	
	public void batchDelete(String[] ids) {
		super.batchDeleteByIDs(VisitsVO.class, ids);
	}
	
	@Override
	protected void beforeDeleteVO(VisitsVO vo) {
		
		super.beforeDeleteVO(vo);
				
		vo.setDeletedTime(new Date());
		vo.setDeletedUserId(new Long(InvocationInfoProxy.getParameter("id")));	
	}
	
	public Object selectFieldsByIds(Object[] ids) {
		Map<String, Object> para = new HashMap<String, Object>();
		para.put("ids", ids);
		return dao.selectList(VisitsVO.class, "selectFieldsByIds", para);
	}
	
	public List<VisitsVO> getScheduleList(Map<String, Object> paramMap) {
		
		paramMap.put("ownerUserId", new Long(InvocationInfoProxy.getParameter("id")));
		
		List<VisitsVO> visitList = dao.selectVoList(VisitsVO.class, "getVisitsList", paramMap);
		
		transVisit(visitList);
		
		return visitList;
	}
	
	public List<String> getScheduleDateList(Map<String, Object> paramMap) {
		paramMap.put("ownerUserId", new Long(InvocationInfoProxy.getParameter("id")));
		List<String> res = new ArrayList<String>();
		List<VisitsVO> visitList = dao.selectVoList(VisitsVO.class, "getVisitsDateList", paramMap);
		for(int i = 0; i < visitList.size(); i++){
			VisitsVO visit = visitList.get(i);
			Date date = visit.getDate();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		    String dateStr = formatter.format(date);
		    res.add(dateStr);
		}
		
		return res;
	}
	
	public VisitsVO getLocation(Long id){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		List<VisitsVO> visitList = dao.selectVoList(VisitsVO.class, "getVisitsLocationList", paramMap);
		return visitList.get(0);
	}
	
	public VisitsVO getSummary(Long id){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		List<VisitsVO> visitList = dao.selectVoList(VisitsVO.class, "getVisitsSummaryList", paramMap);
		return visitList.get(0);
	}

	private List<VisitsVO> transVisit(List<VisitsVO> visitList) {
		
		int listSize = visitList.size();
		if (visitList != null && listSize > 0) {
			
			List<FieldRelation<VisitsVO>> relations = new ArrayList<FieldRelation<VisitsVO>>();
			relations.add(new RefFieldRelation<VisitsVO>(VisitsVO.class, "orgId", new String[]{"orgName"}, orgService, "selectFieldsByIds"));
			new FieldRelationHandler<VisitsVO>().handler(visitList, relations);
			
			//客户拜访计划的特殊处理
			for(int i = 0; i < listSize; i++) {
				VisitsVO visit = visitList.get(i);
				// 转换负责人部门名称
				/*
				UserVO user = visit.getOwnerInfo();
				user = transUser(user);
				visit.setOwnerInfo(user);
				*/
				//因为user mapper的idGetUser返回类型由UserVO改为UserDO所引起的修改
				//（取消在mapper里使用association,改为调用user的getDetail方法）
				Long userId = visit.getOwnerUserId();
				UserVO user = userService.getDetail(userId);
				visit.setOwnerInfo(user);
				
				//获取联系人信息
				String contactIds = visit.getContactId();
				if (!(contactIds.equals(null) || contactIds.equals(""))) {
					String[] contactIdArray = contactIds.split(",");
					visit.setContactInfo(contactService.selectVOByIds(contactIdArray));
				}
			}
		}

		return visitList;
	}
	
	private UserVO transUser(UserVO user) {
		
		List<UserVO> userList = new ArrayList<UserVO>();
		userList.add(user);
		if (userList != null && userList.size() > 0) {
			List<FieldRelation<UserVO>> relations = new ArrayList<FieldRelation<UserVO>>();
			relations.add(new RefFieldRelation<UserVO>(UserVO.class, "deptId", new String[]{"deptName"}, orgService, "selectFieldsByIds"));
			new FieldRelationHandler<UserVO>().handler(userList, relations);
		}

		return userList.get(0);
	}
	
	//获取公司拜访规则
	private VisitruleVO getVisitRule(VisitsVO visit) {
		Map<String, Object> paraMap = new HashMap<>();
		String orgId = InvocationInfoProxy.getParameter("orgid");
		paraMap.put("orgId", orgId);
		long refIndex = getRefIndex();
		paraMap.put("refIndex", refIndex);
		CustomerVO customer = visit.getCumInfo();
		long cumValue = 0;
		if (refIndex == 1) {
			//1为客户级别
			cumValue = customer.getLevel();
		} else if (refIndex == 2) {
			//2为客户类型
			cumValue = customer.getType();
		} else if (refIndex == 3) {
			//3为客户状态（生命周期）
			cumValue = customer.getState();
		}
		paraMap.put("cumEnumValue", cumValue);
		List<VisitruleVO> visitRuleList = visitruleService.getRefList(paraMap);
		return visitRuleList.get(0);
	}
	
	//获取拜访规则类型设置
	public Integer getRefIndex(){
		//TODO 获取拜访规则类型设置
		return 1;
	}
	
	public VisitsVO save(VisitsVO visit){
		return super.saveVO(visit);
	}
	
	public void saveScheduleTaskcard(VisitsVO visit){
		//查询客户拜访对应的拜访规则和任务卡
		dao.getById(VisitsVO.class, visit.getId());
		visit = dao.getById(VisitsVO.class, visit.getId());
		CustomerVO customer = visit.getCumInfo();
		Integer refIndex = getRefIndex();
		Map<String, Object> paraMap = new HashMap<String, Object>();
		paraMap.put("refIndex", refIndex);
		if (refIndex.equals(RefIndexEnum.CUMLEVEL.getValue())) {
			paraMap.put("cumLevel", customer.getLevel());
		} else if (refIndex.equals(RefIndexEnum.CUMTYPE.getValue())) {
			paraMap.put("cumType", customer.getType());
		} else if (refIndex.equals(RefIndexEnum.CUMSTATE.getValue())) {
			paraMap.put("cumState", customer.getState());
		}
		List<VisitruleVO> visitRuleList = visitruleService.getRefList(paraMap);
		if (visitRuleList != null && visitRuleList.size() > 0) {
			VisitruleVO visitRule = visitRuleList.get(0);
			if (visitRule != null) {
				List<VisitruleTaskcardVO> vrtcList = visitRule.getTaskcardList();
				List<ScheduleTaskcardVO> stList = new ArrayList<ScheduleTaskcardVO>();
				if (vrtcList != null && vrtcList.size() > 0) {
					for (VisitruleTaskcardVO vrtc : vrtcList) {
						ScheduleTaskcardVO scheduleTaskcard = new ScheduleTaskcardVO();
						scheduleTaskcard.setScheduleId(visit.getId());
						scheduleTaskcard.setScheduleType(ScheduleTypeEnum.CUSVISIT.getValue());
						scheduleTaskcard.setTaskcardId(vrtc.getTaskcardId());
						scheduleTaskcard.setObjType(vrtc.getMtObjId());
						scheduleTaskcard.setObjBiztype(vrtc.getMtBiztypeId());
						scheduleTaskcard.setRequired(vrtc.getRequired());
						scheduleTaskcard.setOrderNum(vrtc.getOrderNum());
						stList.add(scheduleTaskcard);
					}
				}
				stService.batchSave(stList);
			}
		}
	}
}
